﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.CommandHandler.InvoiceManagements;
using Reporting.API.Application.Commands.Ticketmanagements;
using Reporting.API.DTOs.InvoiceManagementResponseDto;
using Reporting.API.DTOs.TicketmanagementDTO;
using Reporting.API.Utils;
using Reporting.Domain;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.InvoiceManagements;
using Reporting.Infrastructure.Interfaces.Invoicetypes;
using Reporting.Infrastructure.Interfaces.Payees;
using Reporting.Infrastructure.Interfaces.Ticketmanagements;

namespace Reporting.API.Application.CommandHandler.Ticketmanagements
{
    /// <summary>
    /// 开票  --显示所有开票信息
    /// </summary>
    public class GetTicketmanagementCommandHandler : IRequestHandler<GetTicketmanagementCommand, ApiResult<PagingResult<IList<GetpageTicketmanagementResponse>>>>
    {
        private readonly ITicketmanagementRepository  _ticketmanagementRepository;  //开票
        private readonly IInvoicetypeRepository _invoicetypeRepository;  //发票类型
        private readonly IPayeeRepository _payeeRepository;  //开、收票方
        private readonly IMapper _mapper;
        private readonly ILogger<GetTicketmanagementCommandHandler> _logger;
        public GetTicketmanagementCommandHandler(IMapper mapper, ILogger<GetTicketmanagementCommandHandler> logger, IInvoicetypeRepository invoicetypeRepository, IPayeeRepository payeeRepository, ITicketmanagementRepository ticketmanagementRepository)
        {
            _mapper = mapper;
            _logger = logger;
            _invoicetypeRepository = invoicetypeRepository;
            _payeeRepository = payeeRepository;
            _ticketmanagementRepository = ticketmanagementRepository;
        }

        public async Task<ApiResult<PagingResult<IList<GetpageTicketmanagementResponse>>>> Handle(GetTicketmanagementCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取所有开票信息
                var Ticketmanagements = await _ticketmanagementRepository.GetAllAsync();
                // 发票类型（外健）
                var Sourcetypes = await _invoicetypeRepository.GetAllAsync();
                // 发票类型（外健）
                var Payees = await _payeeRepository.GetAllAsync();

                // 外健链接
                var result = from Ticketmanagement in Ticketmanagements
                             join Invoicetype in Sourcetypes on Ticketmanagement.InvoicetypeId equals Invoicetype.InvoicetypeId
                             join Payee in Payees on Ticketmanagement.PayeeId equals Payee.PayeeId
                             select new GetpageTicketmanagementResponse
                             {
                                 Ticketmanagementid = Ticketmanagement.Ticketmanagementid, // 到票管理ID
                                 Arrivalticketnumber = Ticketmanagement.Arrivalticketnumber, // 到票单号
                                 Tickettheme = Ticketmanagement.Tickettheme, // 到票主题
                                 InvoicetypeId = Ticketmanagement.InvoicetypeId, // 发票类型ID（外键）
                                 Ticketarrivaldate = Ticketmanagement.Ticketarrivaldate, // 到票日期
                                 PayeeId = Ticketmanagement.PayeeId, // 收票方ID（外键）
                                 Ticketamountreceived = Ticketmanagement.Ticketamountreceived, // 到票金额
                                 Invoicenumber = Ticketmanagement.Invoicenumber, // 发票号
                                 Ticketmanagementnotes = Ticketmanagement.Ticketmanagementnotes, // 备注
                                 InvoicetypeName = Invoicetype.InvoicetypeName, // 发票类型名称（通过外键关联获取）
                                 PayeeName = Payee.PayeeName // 收票方名称（通过外键关联获取）
                             };



                // 当前页的数据
                var currentData = _mapper.Map<IList<GetpageTicketmanagementResponse>>(result.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize).ToList());

                // 分页
                var pagingResult = new PagingResult<IList<GetpageTicketmanagementResponse>>
                {
                    TotalCount = result.Count(),
                    TotalPage = Math.Ceiling(result.Count() / (double)request.PageSize),
                    Data = currentData
                };

                // 返回成功结果
                return ApiResult<PagingResult<IList<GetpageTicketmanagementResponse>>>.Success(pagingResult, StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询失败");

                // 返回失败结果
                return ApiResult<PagingResult<IList<GetpageTicketmanagementResponse>>>.Fail("查询失败：" + ex.Message, StatusCodeEnum.BadRequest);
            }
        }
    }
}
